<template>
  <a-layout-header class="header">
    <a-row :wrap="false" align="middle">
      <!-- 左侧：纯文字品牌 -->
      <a-col flex="240px">
        <RouterLink to="/">
          <div class="header-left">
            <img class="logo" src="@/assets/logo.png" alt="Logo" />
            <h1 class="site-title" v-scramble>SHU AI</h1>
          </div>
        </RouterLink>
      </a-col>
      <!-- 中间：导航菜单 -->
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="horizontal"
          :items="menuItems"
          @click="handleMenuClick"
        />
      </a-col>
      <!-- 右侧：用户操作区域 -->
      <a-col>
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-dropdown>
              <a-space>
                <a-tooltip
                  :title="`${loginUserStore.loginUser.userName ?? '无名'} · ${loginUserStore.loginUser.userRole ?? ''}`"
                >
                  <a-avatar :src="loginUserStore.loginUser.userAvatar" class="user-avatar" />
                </a-tooltip>
                {{ loginUserStore.loginUser.userName ?? '无名' }}
              </a-space>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="goProfile"> 个人中心 </a-menu-item>
                  <a-menu-item @click="doLogout">
                    <LogoutOutlined />
                    退出登录
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <div v-else>
            <a-button class="login-btn" href="/user/login"><span v-scramble>登录</span></a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </a-layout-header>
</template>

<script setup lang="ts">
import { computed, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { MenuProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/loginUser.ts'
import { LogoutOutlined } from '@ant-design/icons-vue'
import { userLogout } from '@/api/userController.ts'
// 不直接引入页面组件，菜单仅提供路由 key

// 获取登录用户状态
const loginUserStore = useLoginUserStore()
const router = useRouter()
// 当前选中菜单
const selectedKeys = ref<string[]>(['/'])
// 监听路由变化，更新当前选中菜单
router.afterEach((to) => {
  selectedKeys.value = [to.path]
})

// 菜单配置项
const originItems = [
  {
    key: '/',
    label: '首页',
    title: '首页',
  },
  {
    key: '/admin/userManage',
    label: '用户管理',
    title: '用户管理',
  },
  {
    key: '/admin/appManage',
    label: '应用管理',
    title: '应用管理',
  },
  {
    key: '/admin/chatManage',
    label: '对话管理',
    title: '对话管理',
  },
  {
    key: 'others',
    label: h(
      'a',
      { href: 'https://blog.csdn.net/m0_74952497?spm=1000.2115.3001.10640', target: '_blank' },
      'ZYYYYS',
    ),
    title: 'ZYYYYS',
  },
]

// 过滤菜单项
const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    const menuKey = menu?.key as string
    if (menuKey?.startsWith('/admin')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}

// 展示在菜单的路由数组
const menuItems = computed<MenuProps['items']>(() => filterMenus(originItems))

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  const key = e.key as string
  selectedKeys.value = [key]
  // 跳转到对应页面
  if (key.startsWith('/')) {
    router.push(key)
  }
}

// 退出登录
const doLogout = async () => {
  const res = await userLogout()
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}

const goProfile = async () => {
  await router.push('/user/profile')
}
</script>

<style scoped>
.header {
  background: #ffffff;
  padding: 0px 18px;
  border: 1px solid #ececec;
  margin: 10px;
  border-radius: 16px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.04);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo {
  width: 58px;
  height: 58px;
  border-radius: 12px;
}

.site-title {
  margin: 0;
  font-size: 20px;
  color: #111111;
  letter-spacing: 1px;
  font-weight: 800;
}

.ant-menu-horizontal {
  border-bottom: none !important;
}

/* 菜单 hover/active 下划线过渡 */
:deep(.ant-menu-horizontal > .ant-menu-item) {
  position: relative;
}
:deep(.ant-menu-horizontal > .ant-menu-item::after) {
  content: '';
  position: absolute;
  left: 12px;
  right: 12px;
  bottom: 8px;
  height: 4px;
  background: #111111;
  transform: scaleX(0);
  transform-origin: center;
  transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  opacity: 80;
}
:deep(.ant-menu-horizontal > .ant-menu-item:hover::after) {
  transform: scaleX(1);
  opacity: 1;
  transition:
    transform 0.3s cubic-bezier(0.4, 0, 0.2, 1),
    opacity 0.2s ease;
}
:deep(.ant-menu-horizontal > .ant-menu-item-selected::after) {
  transform: scaleX(1);
  opacity: 1;
  transition:
    transform 0.4s cubic-bezier(0.4, 0, 0.2, 1),
    opacity 0.3s ease;
}

.login-btn {
  background: #111111;
  color: #ffffff;
  border: none;
}
.login-btn:hover {
  background: #000000;
  color: #ffffff;
}

.user-avatar {
  box-shadow: 0 0 0 0 rgba(17, 17, 17, 0.25);
  transition:
    transform 0.25s ease,
    box-shadow 0.25s ease;
}
.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
}
</style>
